layui.extend({
    selectN: '/layui_extends/selectN',
    selectM: '/layui_extends/selectM',
    baseConfig : "/js/pages/baseConfig"
}).use(['form','layer','laydate','table','laytpl','element','util','upload','selectN','selectM','baseConfig'],function(){

    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        table = layui.table,
        upload = layui.upload,
        laydate = layui.laydate,
        selectN = layui.selectN,
        baseConfig = layui.baseConfig,
        selectM = layui.selectM;
    var util = layui.util;
    //非管理员需要隐藏collaborateur和导入时间
    var hideCol = true;
    if( baseConfig.checkPrivalege( baseConfig.RECHARGE_LIST_ALL)){
        hideCol = false;
    }

    var tableIns = table.render({
        elem: '#list',
        url : '/recharge/list/',
        text: { none: "Aucun résultat"},
        cellMinWidth : 95,
        height : "full",
        page: true, //开启分页
        limit : 20,
        limits : [20,50,70,100],
        totalRow : true, //开启合计行
        id : "listTable",
        cols : [[
            {field: 'dealTimeFrench', title: "DATE", align:"center", templet:function ( d) {
                    return baseConfig.formatDate( d.dealTimeFrench);
            }},
            {field: 'jobNumber', title: "Identifiant", hide: hideCol, align:"center", templet : function( d) {
                if( d.jobNumber){
                    return d.jobNumber;
                }else{
                    return "未找到员工";
                }
            }},
            {field: 'rechargeTypeName', title: "Méthode", align:"center"},
            {field: 'merchantOrderAmount', title: "Montant", align:"center", totalRow: true,templet : function( d){
                return parseFloat( d.merchantOrderAmount).toFixed(2);
                /*
                var integerV = d.merchantOrderAmount.toString().split(".")[0];
                var floatV = d.merchantOrderAmount.toString().split(".")[1];
                var profix = "";
                if( d.moneyStatus != "6"){
                    //前面加个时钟
             //       profix = "<img src='' class=''/> ";
                }
                var thouend = parseInt(integerV / 1000);
                var str = profix + ( thouend > 0 ? thouend : "") + " " + integerV%1000 + "," + parseFloat( floatV).toFixed(2) + " €";

                return "<div style='width: 40%;text-align: right;margin-right: 30%'>" + str + "</div>" */
            }},
            {field: 'moneyStatus', title: "État", align:"center", templet : function( d){
                switch ( d.moneyStatus) {
                    case "1": return "<span style='color: #FF5722;'>已收款</span>";
                    case "2": return "<span style='color: #FF5722;'>BIEN RECU</span>";
                    case "3": return "<span style='color: #FF5722;'>消费中心转账中</span>";
                    case "4": return "<span style='color: #FF5722;'>RECHARGE EN COUR</span>";
                    case "5": return "<span style='color: #FF5722;'>卡额分配中</span>";
                    case "6": return "<span style='color: #009688;'>RECHARGE REUSSIR</span>";
                }
            }},
            {field: 'updateMoneyStatusThree', title: "Date valeur", align:"center", templet:function ( d) {
                if( d.updateMoneyStatusThree){
                    return baseConfig.formatDate( d.updateMoneyStatusThree);
                }
                return "";
            }},
            {field: 'memo', title: "Remarques", align:"center"},
        ]],
        response : {
            statusCode: 200 //规定成功的状态码，默认：0
        },
        parseData : function( res){ //res 即为原始返回的数据
            return {
                "code": res.code, //解析接口状态
                "msg": res.msg, //解析提示文本
                "count": res.data.count, //数据条数
                "data": res.data.data //解析数据列表
            };
        }
    });

    //添加/修改/详细查看（readonly=true）
    function addOrUpdateOrDetail( data, readonly){
        var index = layui.layer.open({
            title : "添加",
            type : 2,
            area: [600 + 'px', 300 + 'px'],
            shade: 0.4,
            btnAlign: 'r',
            id: "datadefine_" + type, //设定一个id，防止重复弹出
            content : "uploadCustomsClearanceForm.html",
            success : function(){
                var body = layui.layer.getChildFrame( 'body', index);
                if( data){
                    body.find( "input[name=id]").val( data.id).attr( "readonly", readonly);//标识是修改还是新增
                    body.find( "input[name=dataKey]").val( data.dataKey).attr( "readonly", readonly);
                    body.find( "input[name=dataValue]").val( data.dataValue).attr( "readonly", readonly);
                    if( readonly){
                        body.find( "#submitDiv").hide();
                    }
                    form.render();
                }
                body.find( "input[name=type]").val( type).hide();
                setTimeout( function(){
                    layui.layer.tips('点击此处返回数据列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500);
            }
        });
    }

    //加载日期选择框
    laydate.render({
        elem: '#dealStartTime',
        format: 'yyyy-MM-dd',
        trigger: 'click',
        lang: 'en',
        max : 0,
        done: function(value, date){
            $(".search_btn").click();
        }
    });
    laydate.render({
        elem: '#dealEndTime',
        format: 'yyyy-MM-dd',
        trigger: 'click',
        lang: 'en',
        max : 0,
        done: function(value, date){
            $(".search_btn").click();
        }
    });
    /*
    //加载员工工号多选下拉框
    var importUserIdSelect = selectM({
        //元素容器【必填】
        elem: '#importUserIdDiv',
        //候选数据【必填】
        data: "/userAdmin/listForSelect",
        //最多选中个数，默认5
        max : 5,
        //input的name 不设置与选择器相同(去#.)
        name: 'importUserId',
        //值的分隔符
        delimiter: ',',
        tips: "ID",
        //候选项数据的键名
        field: {idName:'id',titleName:'jobNumber'}
    }); */

    //处理权限相关
    handlePrivage();

    //输入money，将触发搜索事件
    $("input[name=payMoney]").on("input propertychange",function(e){
        $(".search_btn").click();
    });
    //输入支付宝订单号
    $("input[name=merchantOrderNo]").on("input propertychange",function(e){
        $(".search_btn").click();
    });
    $("input[name=jobNumber]").on("input propertychange",function(e){
        $(".search_btn").click();
    });

    //搜索【此功能需要后台配合，所以暂时没有动态效果演示】
    $(".search_btn").on("click",function(){
        var paramJson = getSearchParam();
        //校验结束时间不能小于开始时间
        if( paramJson.dealStartTime && paramJson.dealEndTime){
            var dealStartDate = new Date( paramJson.dealStartTime);
            var dealEndDate = new Date( paramJson.dealEndTime);
            if( dealStartDate.getTime() > dealEndDate.getTime()){
                layer.msg( "交易结束时间必须大于交易开始时间");
                return;
            }
        }
        if( paramJson.dealMonth && ( paramJson.dealStartTime || paramJson.dealEndTime)){
            layer.msg( "起止时间和月份只能选择一种作为条件来查询");
            return;
        }
        table.reload("listTable",{
            page: {
                curr: 1 //重新从第 1 页开始
            },
            where: paramJson
        })
    });

    //上传excel文件
    upload.render({
        elem: '#import_excel_btn',
        url: '/file/upload?type=recharImportExcel',
        method : "post",
        accept : "file",
        exts : "xlsx|xls",
        done: function(res){
            if( res.code == 200){
                var excelPath = res.data.filePath;
                var index = layer.msg('导入中，请稍候....',{ icon: 16, time:false, shade:0.8});
                //调用excel解析接口
                $.post( "/recharge/importFromExcel",{
                    "filePath" : excelPath
                },function( res){
                    layer.close( index);
                    if( res.code == 200){
                        var repeats = res.data.repeatDatas;
                        var successCount = res.data.successCount;
                        var errorDatas = res.data.errorDatas;

                        var msg = "导入成功,本次成功导入[" + successCount + "]条数据";
                        if( repeats && repeats.length != 0){
                            msg += "，出现条[" + repeats.length + "]重复导入的数据";
                        }
                        if( errorDatas && errorDatas.length != 0){
                            var errStrs = "";
                            for( var i = 0 ; i < errorDatas.length ; i++){
                                if( i != 0){
                                    errStrs += ",";
                                }
                                errStrs += errorDatas[i].rowNum;
                            }
                            msg += "，出现表格数据{" + errStrs + "}这几行因为格式错误导入失败的数据";
                        }
                        top.layer.alert( msg);
                        tableIns.reload();
                    }else{
                        top.layer.alert( res.msg ? res.msg : "导入失败");
                    }
                });
            }
        }
    });

    $("#import_excel_a").on("click",function(){

        //询问用户确认导入
        var tipHtml = "";
        tipHtml += "<p>1、请先下载模板！</p>";
        tipHtml += "<p>2、文件格式必须与模板完全一致！</p>";
        tipHtml += "<p>3、填写了商品条码，可不填写商品编号、全名！</p>";
        tipHtml += "<p>4、没填写商品条码，商品编号为空时，商品全名不允许为空！！</p>";
        tipHtml += "<p>5、录入的商品条码、商品全名、商品编号等信息必须与系统中一致</p>";
        tipHtml += "<p>6、EXCEL中商品明细不能超过800行</p>";
        tipHtml += "<p>7、上传的商品明细文件必须为.xls/xlsx类型</p>";
        layer.confirm( tipHtml, {icon: 3, title:'导入规则说明'}, function( i){
            //do something
            layer.close( i);
            //触发文件上传按钮的点击时间
            $("#import_excel_btn").triggerHandler( "click");
        });
    });

    //excal导出
    $("#download_excel").on("click",function(){
        var index = layer.msg('导出中，请稍候....',{ icon: 16, time:false, shade:0.8});
        //获取到此时的查询条件
        var paramJson = getSearchParam();
        $.post( "/recharge/exportAsExcel", paramJson, function( res){
            layer.close( index);
            if( res.code == 200){
                var exportCount = res.data.exportCount;
                var filePath = res.data.filePath;
                top.layer.alert( "导出成功");
                layer.confirm( "导出成功,共导出[" + exportCount + "]条数据，确认下载Excel文件？", function( confirmIndex){
                    window.open( filePath);
                    layer.close( confirmIndex);
                });
            }else{
                top.layer.alert( "导出失败");
            }
        });
    });

    //excal模板下载
    $("#download_moden").on("click",function(){
        window.location.href = "/frenchProject/recharImportExcel/rechargeModel.xls";
    });

    $("#getRechargeQrCode").on("click",function(){
        var totalFee = $("input[name=totalFee]").val();
        if( !totalFee){
            layer.alert( "请输入本次收款金额")
            return;
        }
        if( totalFee.toString().split(".").length > 2){
            layer.alert( "收款金额最多只能有两位小数")
            return;
        }
        if( totalFee > 50000 || totalFee < 0.01){
            layer.alert( "本次收款金额范围在0.01-50000之间")
            return;
        }
        //loading
        var loadingIndex = layer.open({ type: 3});
        $.get("/easyEuroClient/getRechargeQrCode?totalFee=" + totalFee,function( res){
            layer.close( loadingIndex);
            if( res.code == 200){
                var data = res.data;
                var nom = data.nom;
                var prenom = data.prenom;
                $("input[name=orderNo]").val( data.orderNo);
                //打开展示二维码的弹窗
                var rechargeQrCodeIndex = layer.open({
                    title: '收款二维码 员工:[' + nom + " " + prenom + '],金额:[' + totalFee + ']€',
                    content: "<img style='border: 1px solid #ccc;' width='400px' height='400px' src='" + data.codeImgUrl + "'>",
                    area:['440px','500px'],
                    btn:[]
                });
                //获取二维码成之后，就开始轮询支付的结果
                queryPayRes( rechargeQrCodeIndex);
            }else if( res.code == 304){
                layer.confirm( "用户登录过期，请重新登录", {icon: 3, title:'登录过期'}, function( i){
                    top.location.href = "/pages/login.html";
                });
            }else{
                top.layer.alert( res.msg);
            }
        });
    });

    /**
     * 轮询后台查询订单支付状态
     * @param orderNo
     */
    function queryPayRes( imgIndex){
        var orderNo = $("input[name=orderNo]").val();
        $.get("/easyEuroClient/queryPayResult?orderNo=" + orderNo,function( res){
            var rechargeRecordModel = res.data;
            //支付成功
            if( res.code == 200 && rechargeRecordModel){
                $("#rechargeQrCode").val( "");
                layer.close( imgIndex);
                top.layer.alert( "收款[EUR][" + rechargeRecordModel.merchantOrderAmount + "]成功到账");
                tableIns.reload();
            }else{
                setTimeout( queryPayRes,1 * 1000);
            }
        });
    }

    //列表操作
    table.on('tool(list)', function(obj){
        var layEvent = obj.event,
            data = obj.data;
        if(layEvent === 'edit'){ //编辑  -暂时不用
            addOrUpdateOrDetail( data, false);
        } else if(layEvent === 'del'){ //删除
            del( data.id);
        } else if(layEvent === 'look'){ //预览
            addOrUpdateOrDetail( data, true);
        }
    });

    //处理权限相关的东西
    function handlePrivage(){
        //判断是否有查看所有数据的权限，如果没有，则隐藏所有员工的这项搜索条件
        if( baseConfig.checkPrivalege( baseConfig.RECHARGE_LIST_ALL)){
            $("#importUserIdDiv").show();
        }else{
            $("#importUserIdDiv").hide();
            $( "input[name=jobNumber]").hide();
        }
        //判断是否有导入/导出excel数据的权限
        if( baseConfig.checkPrivalege( baseConfig.RECHARGE_EXCEL)){
            $("#download_moden").show();
            $("#import_excel_a").show();
            $("#export_excel_btn").show();
        }else{
            $("#download_moden").hide();
            $("#import_excel_a").hide();
            $("#export_excel_btn").hide();
        }
    }

    function getSearchParam(){
        var importUserId = $("input[name=importUserId]").val();
        var payMoney = $("input[name=payMoney]").val();
        var merchantOrderNo = $("input[name=merchantOrderNo]").val();
        var moneyStatus = $("select[name=moneyStatus]").val();
        var dealMonth = $("select[name=dealMonth]").val();
        var dealStartTime = $("input[name=dealStartTime]").val();
        var dealEndTime = $("input[name=dealEndTime]").val();
        var jobNumber = $("input[name=jobNumber]").val();
        var param = {
            "importUserId": importUserId,
            "payMoney": payMoney,
            "merchantOrderNo": merchantOrderNo,
            "moneyStatus": moneyStatus,
            "dealMonth": dealMonth,
            "dealStartTime": dealStartTime,
            "dealEndTime": dealEndTime,
            "jobNumber": jobNumber
        };
        return param;
    }
});
